package com.ly.lypicturebackend.aop;

import com.ly.lypicturebackend.annotation.AuthCheck;
import com.ly.lypicturebackend.exception.BusinessException;
import com.ly.lypicturebackend.exception.ErrorCode;
import com.ly.lypicturebackend.model.entity.User;
import com.ly.lypicturebackend.model.enums.UserRoleEnum;
import com.ly.lypicturebackend.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author luyi
 * @create 2024-12-27-12:12
 */
@Aspect
@Component
public class AuthInterceptor {
    @Resource
    private UserService userService;
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        //注解上的权限
        String mustRole = authCheck.mustRole();
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
        //如果没有该注解，直接放行
        UserRoleEnum mustRoleEnum = UserRoleEnum.getEnumByValue(mustRole);
        if(mustRoleEnum==null){
            return joinPoint.proceed();
        }
        //获取当前用户权限角色
        User loginUser = userService.getLoginUser(request);
        UserRoleEnum userRole = UserRoleEnum.getEnumByValue(loginUser.getUserRole());
        //权限比对
        if(userRole==null){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        //必须拥有管理权限
        if(UserRoleEnum.ADMIN.equals(mustRoleEnum)&&!UserRoleEnum.ADMIN.equals(userRole)){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        return joinPoint.proceed();
    }
}
